import React, { useState, useEffect } from 'react';
import { Button, Divider, Popconfirm } from 'antd';
import { useHistory } from 'react-router-dom';
import { LogoutOutlined, HomeOutlined, LoadingOutlined, RollbackOutlined } from '@ant-design/icons';
import {
  openNotification_util, checkdatavalid_util_formdata, fetchsync_util,
  resultdata_to_formdata, addkey_for_mxdata,
  combile_mxdata_mxcol_util,
} from '../util/util.js'
import Customfielditem_hook from '../newmes/customfielditem_hook.js'
import moment from 'moment'
import 'moment/locale/zh-cn'
import { SaveOutlined } from '@ant-design/icons';
import logo from '../../../img/shipSRM/chlogo.png'
import Oltable_mx_hook from './oltable_mx_hook.js';
import { dropByCacheKey } from 'react-router-cache-route'
import { use_oltable_initformdata, use_oltable_mx_column_initformdata } from './use_sys_config.js';
moment.locale('zh-cn')
var storage = window.localStorage;
import useStore from '../../useStore.js'

const Oltable_form = () => {
  const history = useHistory();
  //动态数据源
  const [dynDatasObject, setdynDatasObject] = useState({
    kfkhdaOptions: [],
    oltable_cp: [], oltable_mj: [], gd_mjmx: []
  })
  /**
   * mxdata:明细数据 delidarr:明细删除id集合 mxcolumn：明细列配置项
   */
  const [formdata, setformdata] = useState(use_oltable_initformdata)
  const [mxdata, setmxdata] = useState([])
  const [delidarr, setdelidarr] = useState([]);
  const [mxcolums, setmxcolums] = useState(use_oltable_mx_column_initformdata)
  const [isloading, setisloading] = useState(true)
  const [selectedRows, setselectedRows] = useState([])
  const [selectedRowKeys, setselectedRowKeys] = useState([])
  const { nowroute, setnowroute,collapsed,setcollapsed } = useStore();

  /**
   * 强制刷新明细表 用于特殊场景
   */
  const [switche, setswitche] = useState(true);
  const forceupdate = () => { setswitche(false) }
  useEffect(() => { switche ? "1" : setswitche(true) }, [switche])


  /**
   * 根据主表数据加载表单和明细
   * @param {*} id 
   */
  const loadformdata = async (id) => {
    let rtdata = await fetchsync_util("/admin/sys/query_oltable_byid", 'POST', { id }, "json")
    let formdatares = rtdata.resultdata.formdata;
    let mxdatares = rtdata.resultdata.mxdata;
    var newformdata = resultdata_to_formdata(formdatares, formdata);
    var newmxdata = addkey_for_mxdata(mxdatares)
    setformdata(newformdata);
    setmxdata(newmxdata);
    setisloading(false)
  }

  // 页面进入加载数据 根据 edit加载表单数据 或者取消loading动画
  useEffect(() => {
    JSON.parse(storage.pre_oltable_item).type == "edit" || JSON.parse(storage.pre_oltable_item).type == "copy"
      ? loadformdata(JSON.parse(storage.pre_oltable_item).data.id) : setisloading(false)
  }, [])



  //设置value  根据业务场景自己定义
  const setfield = (onekey, value, settype) => {
    if (settype == 'single') {
      var newitem = formdata[onekey]
      newitem.value = value
      let newformdata = Object.assign({}, formdata, { [onekey]: newitem });
      setformdata(newformdata)
    }
    else if (settype == "muti") {
      var tansferarr = onekey;
      var selectrow = value;
      var newformdata = {}
      tansferarr.forEach(item => {
        var newitem = formdata[item.target]
        newitem.value = selectrow ? selectrow[item.origin] : ""
        newformdata = Object.assign({}, formdata, { [item.target]: newitem });
      })
      setformdata(newformdata)
    }

  }

  const handlecreatcodebacth = async () => {

    await handleupload_nottz()
    var tododata = []
    selectedRows.length == 0 ? tododata = mxdata : tododata = selectedRows
    var dmjgstr = tododata.filter(item => item.zdbm != 'sys_org_code').map(
      item => `${item.zdbm}: { ifdb: true, bt: false, value: ${item.zdlx == 'Date' ? 'usenowDate()' : '""'}, title: '${item.zdmc}', dataIndex: '${item.zdbm}', inputType: "${item.zdlx == 'String' ? 'input_item'
        : item.zdlx == 'Date' ? 'date_item'
          : item.zdlx == 'Double' ? 'input_number_item'
            : item.zdlx == 'Interger' ? 'input_number_item'
              : item.zdlx == 'Text' ? 'input_text_item'
                : 'input_item'}" },
`).join("")

    formdata.dmjg.value = dmjgstr
    setformdata({ ...formdata })

  }

  
  const handlecreatcodebacth_list = async () => {
    await handleupload_nottz()
    var tododata = []

    selectedRows.length == 0 ? tododata = mxdata : tododata = selectedRows

    var dmjgarr = tododata.filter(item => item.zdbm != 'sys_org_code').map(
      item => `{ show: true, title: "${item.zdmc}", key: "${item.zdbm}" },
`)

    dmjgarr.unshift(`{ show: true, title: "序号", key: "xuhao" },
`)
    formdata.dmjg.value = dmjgarr.join("")
    setformdata({ ...formdata })
  }



  const handlecreatcodebacth_mx = async () => {
    await handleupload_nottz()
    var tododata = []
    selectedRows.length == 0 ? tododata = mxdata : tododata = selectedRows
    var dmjgstr = tododata.filter(item => item.zdbm != 'sys_org_code').map(
      item => ` { ifdb: true, bt: false, defalut_v: ${item.zdlx == 'Date' ? 'usenowDate()' : '""'},value: ${item.zdlx == 'Date' ? 'usenowDate()' : '""'}, title: '${item.zdmc}', dataIndex: '${item.zdbm}', inputType: "${item.zdlx == 'String' ? 'input_item'
        : item.zdlx == 'Date' ? 'date_item'
          : item.zdlx == 'Double' ? 'input_number_item'
            : item.zdlx == 'Interger' ? 'input_number_item'
              : item.zdlx == 'Text' ? 'input_text_item'
                : 'input_item'}" },
  `).join("")

    formdata.dmjg.value = dmjgstr
    setformdata({ ...formdata })

  }

  //提交方法
  const handleupload = async () => {
    var checkobj = checkdatavalid_util_formdata(formdata)
    checkobj.rtmessage == '表单数据验证通过！' ? 1 : openNotification_util(checkobj.rtmessage, "cry")
    if (!checkobj.rtstatus) { return; }
    else;

    //校验明细字段
    const pattern = /^[a-zA-Z_]+(?:_\d+)?$/;
    var checkmxtemp = false
    mxdata.forEach(item => {
      if (!pattern.test(item.zdbm)) {
        checkmxtemp = true;
        return;
      }
      else;
    })
    if (checkmxtemp) {
      openNotification_util("输入不符合要求，字段编码只允许录入字母，下划线，数字，存在数字时只能以数字结尾");
      return
    }
    else;

    if (!pattern.test(formdata.table_name.value)) {
      openNotification_util("输入不符合要求，数据库表只允许录入字母，下划线，数字，存在数字时只能以数字结尾");
      return
    }
    else;

    //拼接明细
    var uploadurl = "";
    if (JSON.parse(storage.pre_oltable_item).type == "add" ||
      JSON.parse(storage.pre_oltable_item).type == "copy") {
      uploadurl = "/admin/sys/add_oltable"
      mxdata.forEach(item => item.zdzt = '未同步')
    }
    else if (JSON.parse(storage.pre_oltable_item).type == "edit") {
      uploadurl = "/admin/sys/update_oltable"
      formdata.sftb.value = '未同步'

    }
    else;

    JSON.parse(storage.pre_oltable_item).type == "copy" ? formdata.sftb.value = '未同步' : 1

    var newmxdatalist = combile_mxdata_mxcol_util(mxdata, mxcolums)
    formdata.del_zd.value = delidarr

    let rtdata = await fetchsync_util(uploadurl, 'POST', { formdata, mxdata: newmxdatalist, delidarr: delidarr, storage: storage }, "json")
    setformdata(rtdata.resultdata.formdata);
    var newmxdata = addkey_for_mxdata(rtdata.resultdata.mxdata)
    setmxdata(newmxdata);
    setdelidarr([])
    dropByCacheKey('oltable_form')
    dropByCacheKey('oltable_list')
    setnowroute({route:"/shipSRM/sys/oltable_list",title:"在线表单",closeroute:"/shipSRM/sys/oltable_form"})
  
  }     



  //提交方法
  const handleupload_nottz = async () => {
    var checkobj = checkdatavalid_util_formdata(formdata)
    checkobj.rtmessage == '表单数据验证通过！' ? 1 : openNotification_util(checkobj.rtmessage, "cry")
    if (!checkobj.rtstatus) { return; }
    else;

    //校验明细字段
    const pattern = /^[a-zA-Z_]+(?:_\d+)?$/;
    var checkmxtemp = false
    mxdata.forEach(item => {
      if (!pattern.test(item.zdbm)) {
        checkmxtemp = true;
        return;
      }
      else;
    })
    if (checkmxtemp) {
      openNotification_util("输入不符合要求，字段编码只允许录入字母，下划线，数字，存在数字时只能以数字结尾");
      return
    }
    else;

    if (!pattern.test(formdata.table_name.value)) {
      openNotification_util("输入不符合要求，数据库表只允许录入字母，下划线，数字，存在数字时只能以数字结尾");
      return
    }
    else;

    //拼接明细
    var uploadurl = "";
    if (JSON.parse(storage.pre_oltable_item).type == "add" ||
      JSON.parse(storage.pre_oltable_item).type == "copy") {
      uploadurl = "/admin/sys/add_oltable"
      mxdata.forEach(item => item.zdzt = '未同步')
    }
    else if (JSON.parse(storage.pre_oltable_item).type == "edit") {
      uploadurl = "/admin/sys/update_oltable"
      formdata.sftb.value = '未同步'

    }
    else;

    JSON.parse(storage.pre_oltable_item).type == "copy" ? formdata.sftb.value = '未同步' : 1

    var newmxdatalist = combile_mxdata_mxcol_util(mxdata, mxcolums)
    formdata.del_zd.value = delidarr

    let rtdata = await fetchsync_util(uploadurl, 'POST', { formdata, mxdata: newmxdatalist, delidarr: delidarr, storage: storage }, "json")
    setformdata(rtdata.resultdata.formdata);
    var newmxdata = addkey_for_mxdata(rtdata.resultdata.mxdata)
    setmxdata(newmxdata);
    setdelidarr([])

  }



  const renderfileditem = () => {
    var formdataarr = []
    for (var formitemkey in formdata) {
      formdata[formitemkey].inputType == "none" ? "" : formdataarr.push(formdata[formitemkey])
    }
    formdataarr.sort((a, b) => parseInt(a.xuhao) - parseInt(b.xuhao));
    var renderstr = formdataarr.map(item => {
      var rtitem = item.input_type == "space_item" ?
        <Customfielditem_hook form={formdata} item={{ inputType: "none" }}
          handlechange={(key, value, settype) => { setfield(key, value, settype) }} />
        :
        <Customfielditem_hook form={formdata} item={formdata[item.dataIndex]}
          dynDatasObject={dynDatasObject}
          handlechange={(key, value, settype) => { setfield(key, value, settype) }} />
      return rtitem
    }
    )
    return renderstr
  }




  return (

    <div style={{    height: "94%", backgroundColor: `#F1F1F1`,right:"1%",top:"4vh",overflow:"hidden",
      backgroundSize: "100% 100%", width: collapsed?"94%":"84%",   color: "white", fontSize: "0.8rem",
      position:"absolute",
      }}>



      <div style={styles.kshcontainer}>
        <div style={{
          fontSize: "0.7rem", position: "relative", width: "96%", marginLeft: "2%", backgroundColor: "", display: "flex",
          textIndent: "1rem", justifyContent: "flex-start", alignContent: "flex-start", flexWrap: "wrap"
        }}>
          {renderfileditem()}
        </div>
    

        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <Button type="primary" onClick={handleupload}
          style={{ width: "6rem", height: '1.7rem', fontSize: "0.7rem", borderRadius: "5px", marginTop: "0.6rem" }}>
          <SaveOutlined />{JSON.parse(storage.pre_oltable_item).type == "add" ? "保存" : "修改"}</Button>

        &nbsp;&nbsp;
        <Popconfirm title="保存并生成代码结构——主表？" onConfirm={handlecreatcodebacth}>
          <Button type="primary"
            style={{
              width: "9rem", height: '1.7rem', fontSize: "0.7rem", borderRadius: "5px",
              marginTop: "0.6rem"
            }}>
            生成代码结构_主表
          </Button>
        </Popconfirm>


        &nbsp;&nbsp;
        <Popconfirm title="保存并生成代码结构——明细？" onConfirm={handlecreatcodebacth_mx}>
          <Button type="primary"
            style={{
              width: "9rem", height: '1.7rem', fontSize: "0.7rem", borderRadius: "5px",
              marginTop: "0.6rem"
            }}>
            生成代码结构_明细
          </Button>
        </Popconfirm>

        &nbsp;&nbsp;
        <Popconfirm title="保存并生成代码结构——列表？" onConfirm={handlecreatcodebacth_list}>
          <Button type="primary"
            style={{
              width: "9rem", height: '1.7rem', fontSize: "0.7rem", borderRadius: "5px",
              marginTop: "0.6rem"
            }}>
            生成代码结构_列表
          </Button>
        </Popconfirm>




        {/* 主表区域结束 */}
        <Divider></Divider>

        {/* 明细表 */}
        <div style={styles.linestyle}>
          <div style={styles.lineleft}><span style={{ color: "grey" }}>&nbsp;字段配置</span></div>
        </div>
        {isloading ?
          (<div style={{ width: "10%", height: "10%", position: "absolute", left: "50%", top: "49%", color: "#14d9cc" }}>            <LoadingOutlined /></div>)
          :
          <div style={{ position: "relative", width: "100%", overflowX: "scroll", paddingLeft: "3%", paddingRight: "3%" }}>
            {switche && <Oltable_mx_hook colmuns={mxcolums} datasource={mxdata}
              onepageheight="10vh"
              styleobj={{ width: `${mxcolums.length * 7}rem`, height: "70%" }}
              dynDatasObject={dynDatasObject}
              formdata={formdata}
              handledelid={ids => { ids.length !== 0 ? setdelidarr([...delidarr, ...ids]) : ''; }}
              handgetmxdata={(tabledata) => {
                addkey_for_mxdata(tabledata)
                setmxdata(tabledata)
              }}
              setselectedRowKeys={e => setselectedRowKeys(e)}
              setselectedRows={e => setselectedRows(e)}
              forceupdate={forceupdate}
            />}</div>
        }


      </div>
    </div>
  )
}


export default Oltable_form

var styles = {
  maincontainer: {
    height: "100vh", backgroundColor: `white`,
    backgroundSize: "100% 100%", width: "100%", position: "absolute", left: "0", color: "white", fontSize: "0.8rem"
  },
    topcontainer: {
    width: "100%", height: "10vw", backgroundImage: "linear-gradient(to bottom,#e4e5eb , white)", paddingTop: "3vw",
    position: "relative", fontSize: "0.89rem", textIndent: "2rem", fontWeight: "800", color: "#a91f24", borderRadius: "0 0 15px 15px"
  },
butdcstyle: { paddingLeft:"1vw",paddingRight:"1vw",height: "2vw", position: "absolute", right: "1%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0.4rem", borderRadius: "0 0 0.3vw 0.3vw" },
butmainstyle: {paddingLeft:"1vw", height: "2vw", position: "absolute", right: "6.5%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0.4rem", borderRadius: "0 0 0.3vw 0.3vw" },
butbackstyle: { borderRadius: "0.4rem", backgroundColor: "#a91f24", height: "2vw", position: "absolute", right: "12%", top: "0%",fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw"},
  kshcontainer: {
    width: "98%", height: "95%", position: "absolute", top: "3%", left: "1%", backgroundColor: "white", color: "black",
    borderRadius: "10px",overflowY:"scroll"
  },
  linestyle: { height: "1.8rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },
  lineleft: { width: "100%", height: "100%", position: "absolute", left: "0%", textAlign: "left", lineHeight: "2rem", 
    fontSize: "14px", fontWeight: "500",color: "#a91f24",textIndent:"2rem",letterSpacing:"0.05rem" },

}

